//
//  YTXAnalysis.m
//  p4
//
//  Created by Javen Wang on 3/16/15.
//  Copyright (c) 2015 com.baidao. All rights reserved.
//

#import "YSUserManager.h"
#import "YSServiceManager.h"
//#import "EFSServiceManager.h"
#import "YTXRequest.h"
#import "YGUploadAnalyticsEntity.h"
#import <AFNetworking/AFNetworking.h>
#import <UMMobClick/MobClick.h>
#import <FMDB/FMDB.h>
#import <YTXUtilCategory/SSNetworkInfo.h>
#import "TalkingData.h"
#import "EFSAnalytics.h"
#import <AdSupport/ASIdentifierManager.h>



//static const NSTimeInterval REPORT_TIME_INTERVAL = 180;
NSString *const CREATE_TABLE = @"CREATE TABLE IF NOT EXISTS EFSAnalytics (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT);";
NSString *const QUERY_SQL = @"SELECT * FROM EFSAnalytics ORDER BY id;";
NSString *const INSERT_SQL = @"INSERT INTO EFSAnalytics (content) VALUES (?);";
NSString *const DELETE_SQL = @"DELETE FROM EFSAnalytics WHERE id <=";
NSInteger const maxCount = 20;

@interface EFSAnalytics ()
@property (nonatomic) FMDatabaseQueue* dbQueue;
@property (nonatomic) dispatch_queue_t queue;
@property (nonatomic) NSTimeInterval timestamp;
@property (nonatomic, strong)  NSNumber* lastId;
@end

@implementation EFSAnalytics

+ (instancetype)sharedAnalytics
{
    static EFSAnalytics* sharedAnalytics = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedAnalytics = [[self alloc] init];
        sharedAnalytics.sourceType = @"";
        sharedAnalytics.sourceId = @"";
        /** 操作数据库对列必须为串行队列,全局队列不是串行队列 */
        sharedAnalytics.queue = dispatch_queue_create("com.baidao.ylwh.analyticsqueue", DISPATCH_QUEUE_SERIAL);
        //建表
        [sharedAnalytics createAnalyticsTable];
    });
    return sharedAnalytics;
}


- (void)createAnalyticsTable
{
    dispatch_async(self.queue, ^{
        __block BOOL result;
        [self.dbQueue inDatabase:^(FMDatabase* db) {
            result = [db executeStatements:CREATE_TABLE];

            if (!result) {
                NSString* message = @"error, failed to create EFSAnalyticsTable";
                LGlog(@"创建统计数据库失败:%@", message);
            }
        }];
    });
}

+ (void)start
{
    dispatch_async([EFSAnalytics sharedAnalytics].queue, ^{
        
        NSMutableArray* records = [NSMutableArray new];
        __block NSString* postBody = @"[";
        
        [[EFSAnalytics sharedAnalytics].dbQueue inDatabase:^(FMDatabase* db) {
            
            FMResultSet* rs = [db executeQuery:QUERY_SQL];
            
            while ([rs next]) {
               postBody = [[postBody stringByAppendingString:[rs stringForColumn:@"content"]] stringByAppendingString:@","];
                
                [records addObject:[rs stringForColumn:@"content"]];
                [EFSAnalytics sharedAnalytics].lastId = @([rs longLongIntForColumn:@"id"]);
            }
        }];
        
        if (records.count == 0) return;
        postBody = [postBody stringByReplacingCharactersInRange:NSMakeRange(postBody.length-1, 1) withString:@"]"];
        NSDictionary *params = @{@"data":objectOrEmptyStr(postBody)};
        NSLog(@"postBody:%@",postBody);
        YTXRequest *request = [YTXRequest requestWithName:@"config.uploadAnalyticsAction"];
        NSLog(@"request:%@",request.requestUrl);
        [request setRequestSerializerType:YTXRequestSerializerTypeHTTP];
        [request sendWithParameters:params success:^(id response) {
            
            NSInteger errorCode = [((NSNumber *)response[@"errcode"]) integerValue];
            errorCode == 0 ? [EFSAnalytics clearEvent] : nil ;
            
        } failure: ^(YTXRequest *request){
            NSError *error = [NSError errorWithDomain:@"EFS" code:0 userInfo:@{EFS_ERROR_MESSAGE_KEY:@"上传统计行为出错"}];
//            LGlog(request.requestUrl, request.requestMethod, params, nil, error);
        }];
    });
}

+ (void)clearEvent{
    
    dispatch_async([EFSAnalytics sharedAnalytics].queue, ^{
        [[EFSAnalytics sharedAnalytics].dbQueue inDatabase:^(FMDatabase* db) {
            BOOL result = [db executeUpdate:[NSString stringWithFormat:@"%@%@",DELETE_SQL,[EFSAnalytics sharedAnalytics].lastId]];
            if (!result) {
                LGlog(@"删除失败");
            }
        }];
    });
}

+ (void)event:(NSString*)eventId
       action:(NSString *)action
         desc:(NSString *)desc
         data:(NSDictionary*)data
{

#if !DEBUG
//        [self locationEvent:eventId
//                     action:action
//                       desc:desc
//                       data:data];
//    if (data) {
//        [MobClick event:eventId attributes:data];
//        [TalkingData trackEvent:eventId label:eventId parameters:data];
//    } else {
//        [MobClick event:eventId];
//        [TalkingData trackEvent:eventId];
//    }
    LGlog(@"debug");
#else/** 只有线上环境才统计 */
    if (data) {
        [MobClick event:eventId attributes:data];
        [TalkingData trackEvent:eventId label:eventId parameters:data];
    } else {
        [MobClick event:eventId];
        [TalkingData trackEvent:eventId];
    }
#endif
}

+ (void)locationEvent:(NSString*)eventId
               action:(NSString *)action
                 desc:(NSString *)desc
                 data:(NSDictionary*)data
{
    dispatch_async([EFSAnalytics sharedAnalytics].queue, ^{
        
        [[EFSAnalytics sharedAnalytics].dbQueue inDatabase:^(FMDatabase* db) {

            NSDictionary *jsonDict = [self collectEventInfo:eventId
                                                     action:action
                                                       desc:desc
                                                       data:data];
            NSString *jsonStr = [EFSAnalytics stringFromDict:jsonDict];
            NSLog(@"jsonStr:%@",jsonStr);
            BOOL result = [db executeUpdate:INSERT_SQL, jsonStr];
            if (!result) {
                LGlog(@"本地数据统计出错:%@ 参数:%@",eventId ,jsonStr);
            }
        }];
    });
    [self calculateCount];
}

+ (void)calculateCount
{

    dispatch_async([EFSAnalytics sharedAnalytics].queue, ^{
        //计算一下当前的数据量
            __block int count = 0;
            [[EFSAnalytics sharedAnalytics].dbQueue inDatabase:^(FMDatabase* db) {
                FMResultSet* rs = [db executeQuery:QUERY_SQL];
                while ([rs next]) {
                    ++count;
                }
            }];

            if (count >= maxCount) {
                [self start];
            }
 
    });
}

+ (NSDictionary*)collectEventInfo:(NSString*)event
                           action:(NSString *)action
                             desc:(NSString *)desc
                             data:(NSDictionary*)data
{
    data = data ? : @{};
    NSString *dataJsonStr = [EFSAnalytics stringFromDict:data];
    YGUploadAnalyticsEntity *entity = [YGUploadAnalyticsEntity new];
    entity.data = dataJsonStr;
    entity.activity = objectOrEmptyStr(event);
    entity.action = objectOrEmptyStr(action);
    entity.describe = desc;
    return [entity dictionaryValue];
}

- (FMDatabaseQueue*)dbQueue
{
    if (_dbQueue == nil) {
        NSString* dbName = @"EFSAnalytics.db";
        NSString* documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString* dbPath = [documentPath stringByAppendingPathComponent:dbName];
        NSLog(@"dbPath:%@",dbPath);
        _dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
    }
    return _dbQueue;
}

+ (NSString *)stringFromDict:(NSDictionary *)dict {
    
    NSError* error;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:kNilOptions
                                                         error:&error];
    
    return error ? @"" : [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

#pragma mark - 统计事件

+ (void)analyticsTabBarWithIndex:(NSInteger )index {
    NSString *eventActionStr = @[EFS_Tab_Main,EFS_Tab_Quotation,EFS_Tab_Trade,EFS_Tab_Live,EFS_Tab_Mine][index];
    NSString *actionStr = @[@"首页",@"行情",@"交易",@"视频",@"我的"][index];
    [EFSAnalytics
     event:eventActionStr
     action:actionStr
     desc:nil
     data:nil];
}

/** 平台介绍 */
+ (void)analyticsAboutYRY{
    [EFSAnalytics
     event:EFS_Main_AboutYRY
     action:@"首页_关于我们"
     desc:nil
     data:nil];

}

/** 百家专栏 */
+ (void)analyticsArticles{
    [EFSAnalytics event:EFS_Main_Articles action:@"首页_专家视点" desc:nil data:nil];
}

/** 财经日历 */
+ (void)analyticsCalendar{
    [EFSAnalytics event:EFS_Main_Calendar action:@"首页_财经日历" desc:nil data:nil];
}

/** 直播 */
+ (void)analyticsLive{
    [EFSAnalytics event:EFS_Main_Live action:@"首页_直播" desc:nil data:nil];
}

/** 量化指标 */
+ (void)analyticsGuide{
    [EFSAnalytics event:EFS_Main_Guide action:@"首页_量化指标" desc:nil data:nil];
}

/** 新手入门 */
+ (void)analyticsNewbie{
    [EFSAnalytics event:EFS_Main_Newbie action:@"首页_新手入门" desc:nil data:nil];
}

/** 立即开户 */
+ (void)analyticsMainOpenAccount{
    [EFSAnalytics event:EFS_Main_OpenAccount action:@"首页_开户" desc:nil data:nil];
}

+ (void)analyticsOpenAccount {
    [EFSAnalytics event:EFS_OpenAccount action:@"开户" desc:nil data:nil];
}

/** 行情中心 */
+ (void)analyticsQuotation{
    [EFSAnalytics event:EFS_Main_Quotation action:@"首页_行情中心" desc:nil data:nil];
}

/** 新手入门 */
+ (void)analyticsGreenHands{
    [EFSAnalytics event:EFS_Main_GreenHands action:@"首页_新手入门" desc:nil data:nil];
}

/** 委托交易 */
+ (void)analyticsTrade{
    [EFSAnalytics event:EFS_Main_Trade action:@"首页_委托交易" desc:nil data:nil];
}

/** 王牌导师 */
+ (void)analyticsTrumpCard{
    [EFSAnalytics event:EFS_Main_TrumpCard action:@"首页_王牌导师" desc:nil data:nil];
}



/** 首页开放托管 */
+ (void)analyticsTuoGuan{
    [EFSAnalytics event:EFS_Main_TuoGuan action:@"首页_开放托管" desc:nil data:nil];

}
/** 首页发售列表 */
+ (void)analyticsPutOnSale{
    [EFSAnalytics event:EFS_Main_PutOnSale action:@"首页_发售列表" desc:nil data:nil];
    
}
/** 首页交易中心 */
+ (void)analyticsTradeCenter{
    [EFSAnalytics event:EFS_Main_TradeCenter action:@"首页_交易中心" desc:nil data:nil];
    
}






+ (void)analyticsCustomerService
{
    [EFSAnalytics event:EFS_EFSService action:@"客服" desc:nil data:nil];
}

+ (void)analyticsMainFeedback
{
    [EFSAnalytics event:EFS_Main_Feedback action:@"" desc:@"意见反馈" data:nil];
}

+ (void)analyticsMainFinanceMore
{
    [EFSAnalytics event:EFS_Main_Finance_More action:@"财经要闻更多" desc:nil data:nil];
}

+ (void)analyticsYGLogin
{
    [EFSAnalytics event:EFS_JY_YG action:@"粤贵登录" desc:@"login"  data:nil];
}

+ (void)analyticsJGLogin
{
    [EFSAnalytics event:EFS_JY_JG action:@"津贵登录" desc:@"login" data:nil];
}

+ (void)analyticsYGRechargeWithData:(NSDictionary *)data
{
    [EFSAnalytics event:EFS_JY_YG action:@"粤贵入金" desc:@"recharge" data:data];
}

+ (void)analyticsYGWithdrawWithData:(NSDictionary *)data
{
    [EFSAnalytics event:EFS_JY_YG action:@"粤贵出金" desc:@"recharge" data:data];
}

+ (void)analyticsYGBuyWithData:(NSDictionary *)data
{
    [EFSAnalytics event:EFS_JY_YG action:@"粤贵买入" desc:@"buy" data:data];
}

+ (void)analyticsYGSellWithData:(NSDictionary *)data
{
    [EFSAnalytics event:EFS_JY_YG action:@"粤贵卖出" desc:@"sell" data:data];
}

+ (void)analyticsYGCloseWithData:(NSDictionary *)data
{
    [EFSAnalytics event:EFS_JY_YG action:@"粤贵平仓" desc:@"close" data:data];
}

@end
